package org.itboys.mobile.service.mongo.mobile;

import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.utils.common.DistanceUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.kitchen.conmon.Finals;
import org.itboys.kitchen.entity.mongo.village.KitchenVillage;
import org.itboys.mobile.entity.mongo.SundayAddress;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_收获地址_service_移动端
 */
@Service
public class KitchenMobileVillageService extends BaseMongoService<KitchenVillage>{
    @Autowired
    private SundayMobileAddressService addressService;
    @Resource(name = "kitchenDs")
    private MongoDataSource kitchenDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return kitchenDataSource;
    }

    @Override
    protected Class<KitchenVillage> getEntityClass() {
        return KitchenVillage.class;
    }

    //

    /**
     * 获取所有小区。市-小区树形结构。小区按拼音首字母排序
     */
    public List<Map<String,Object>> getVillageByTree(){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        List<KitchenVillage> villages = super.list(param);
        Collections.sort(villages, new Comparator<KitchenVillage>() {
            @Override
            public int compare(KitchenVillage village1, KitchenVillage village2) {
                if(StringUtils.isNotEmpty(village1.getPyszm())
                        &&StringUtils.isNotEmpty(village2.getPyszm())){
                    return village1.getPyszm().compareTo(village2.getPyszm());
                }else{
                    return -1;
                }
            }
        });












       List<Map<String,Object>> cityResults = new ArrayList<Map<String,Object>>();

       for(KitchenVillage city:villages){
           Map<String,Object> cityResult = new HashMap<String,Object>();
           cityResult.put("id",0l);
           cityResult.put("name",city.getCityName());
           cityResult.put("pyszm",null);
           cityResults.add(cityResult);

       }
        //获取城市，去除重复的城市
        for (int i = 0; i < cityResults.size(); i++){  //外循环是循环的次数
            for (int j = cityResults.size() - 1 ; j > i; j--)  {//内循环是 外循环一次比较的次数
                String cityName1=(String)cityResults.get(i).get("name");
                String cityName2=(String)cityResults.get(j).get("name");
                if (cityName1.equalsIgnoreCase(cityName2)){
                    cityResults.remove(j);
                }

            }
        }
        //组装树结构。city-小区首字母-小区
        //城市
        for(Map<String,Object> cityResult:cityResults){
           List<Map<String,Object>> pyszmResults = new ArrayList<Map<String,Object>>();
            String cityName =(String)cityResult.get("name");
            //拼音首字母1（需要去重）
            for(KitchenVillage p:villages){
                if(cityName.equalsIgnoreCase(p.getCityName())){
                    Map<String,Object> pyszmResult = new HashMap<String,Object>();
                    pyszmResult.put("id",0l);
                    pyszmResult.put("name",p.getPyszm());
                    pyszmResult.put("pyszm",p.getPyszm());
                    pyszmResults.add(pyszmResult);
                }
            }
            //拼音首字母2(去重)
            for (int i = 0; i < pyszmResults.size(); i++){  //外循环是循环的次数
                for (int j = pyszmResults.size() - 1 ; j > i; j--)  {//内循环是 外循环一次比较的次数
                    String pyszm1=(String)pyszmResults.get(i).get("pyszm");
                    String pyszm2=(String)pyszmResults.get(j).get("pyszm");
                    if (pyszm1.equalsIgnoreCase(pyszm2)){
                        pyszmResults.remove(j);
                    }

                }
            }


            //拼音首字母3，匹配小区

            for(Map<String,Object> pyszmResult:pyszmResults){
                String pyszm=String.valueOf(pyszmResult.get("pyszm"));
                    List<Map<String,Object>> villageResults = new ArrayList<Map<String,Object>>();

                    for(KitchenVillage v:villages){
                        if(pyszm.equalsIgnoreCase(v.getPyszm())){
                            Map<String,Object> villageResult = new HashMap<String,Object>();
                            villageResult.put("id",v.getId());
                            villageResult.put("name",v.getName());
                            villageResult.put("pyszm",v.getPyszm());
                            villageResults.add(villageResult);
                        }
                    }
                    pyszmResult.put("children",villageResults);
                }




            cityResult.put("children",pyszmResults);
        }




       return cityResults;
    }

    /**
     * 根据经纬度获取最近的10个小区
     * @param longitude
     * @param latitude
     * @return
     */
    public List<Map<String,Object>> getVillageByLocation(String longitude,String latitude){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        List<KitchenVillage> villages = super.list(param);
        List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();

        for(KitchenVillage village:villages){
            Map<String,Object> result = new HashMap<String,Object>();
            result.put("id",village.getId());
            result.put("name",village.getName());
            result.put("pyszm",village.getPyszm());
            result.put("distance", DistanceUtils.GetDistance(
                    Double.valueOf(village.getLongitude()),
                    Double.valueOf(village.getLatitude()),
                    Double.valueOf(longitude),
                    Double.valueOf(latitude)
                    ));
            results.add(result);
            }
        //按距离排序
        Collections.sort(results, new Comparator<Map<String,Object>>() {
            @Override
            public int compare(Map<String,Object> v1, Map<String,Object> v2) {
                Double distance1= v1.get("distance")==null?0:(Double)v1.get("distance");
                Double distance2=  v1.get("distance")==null?0:(Double)v2.get("distance");
                return  distance1.compareTo(distance2);
            }
        });
        //只取前10个
        if(results.size()>10){
            results = results.subList(0,9);
        }
        return results;
    }

    /**
     * 获取用户小区，从收货地址中获取
     * @param memberId
     * @return
     */
    public List<Map<String,Object>> getMemberVillage(Long memberId){
        List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("memberId",memberId);

        List<Long> villageIds = new ArrayList<Long>();
        List<SundayAddress> addresses = addressService.list(param);
        for(SundayAddress address:addresses){
                villageIds.add(address.getVillageId());
        }
        if(ListUtil.isNull(villageIds))return results;
        param.clear();
        param.put("isDeleted",0);
        param.put("id in",villageIds);
        List<KitchenVillage> villages=super.list(param);
        for(KitchenVillage village:villages){
            Map<String,Object> result = new HashMap<String,Object>();
            result.put("id",village.getId());
            result.put("name",village.getName());
            results.add(result);
        }
        return results;


    }
}
